package com.hifar.test.unit.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.log.AutoLogUtils;
import com.hifar.plat.baseModal.service.IBaseOssFilesService;
import com.hifar.plat.officUtil.ExcelTemplateUtil;
import com.hifar.sys.*;
import com.hifar.test.standardbase.pojo.HfResStandard;
import com.hifar.test.unit.pojo.HfPrjUnitBase;
import com.hifar.test.unit.service.IHfPrjUnitBaseService;
import com.hifar.test.unitclassify.pojo.HfPrjUnitClassify;
import com.hifar.test.unitclassify.service.IHfPrjUnitClassifyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 项目-检测项目 前端控制器 default
 * </p>
 *
 * @author wangkepeng
 * @since 2024-12-05 09:02:10
 */
@RestController
@RequestMapping("/api/busi/test/hfPrjUnitBaseController")
@Api(tags = "项目-检测项目功能")
public class HfPrjUnitBaseController {

    @Autowired
    private IHfPrjUnitBaseService hfPrjUnitBaseService;

    @Autowired
    private IBaseOssFilesService baseOssFilesService;

    @Autowired
    private IHfPrjUnitClassifyService hfPrjUnitClassifyService;

    @Autowired
    private AutoLogUtils autoLogUtils;


    @PostMapping(value = "/list")
    @ApiOperation(value = "项目-检测项目功能:分页查询列表")
    public BusiResponse list(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        QueryWrapper<HfPrjUnitBase> queryWrapper = RequestConver.getPostParam(pageInfo);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        queryWrapper.ne("del_flag", "1");
        String classifyId = StringUtils.trimNull(pageInfo.get("classifyId"));
        if (!"".equals(classifyId)) {
            queryWrapper.eq("classify_id", classifyId);
        }

        if (queryWrapper != null && pageInfo.size() > 0) {
            Page<HfPrjUnitBase> page = new Page<>((Integer) pageInfo.get("pageNo"), (Integer) pageInfo.get("pageSize"));
            Page<HfPrjUnitBase> page1 = hfPrjUnitBaseService.page(page, queryWrapper);
            /*计算分页信息返回给前端*/
            PageResult pageResult = SystemUtil.parsePage(page, page1);
            return BusiResponse.OK(pageResult);
        } else {
            return BusiResponse.error("参数不正确！");
        }
    }

    @PostMapping(value = "/listAll")
    @ApiOperation(value = "项目-检测项目功能:查询列表(不带分页)")
    public BusiResponse<List<HfPrjUnitBase>> listAll(HttpServletRequest request) {

        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);


        QueryWrapper<HfPrjUnitBase> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("del_flag", "1");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);

        String classifyId = StringUtils.trimNull(pageInfo.get("classifyId"));
        if (!"".equals(classifyId)) {
            queryWrapper.eq("classify_id", classifyId);
        }
        queryWrapper.orderByAsc("row_sort");
        queryWrapper.orderByDesc("create_time");
        List<HfPrjUnitBase> list = hfPrjUnitBaseService.list(queryWrapper);
        return BusiResponse.OK(list);
    }

    @PostMapping(value = "/add")
    @ApiOperation(value = "项目-检测项目功能:新增")
    public BusiResponse add(@RequestBody HfPrjUnitBase hfPrjUnitBase) {
        if (hfPrjUnitBase.getSecretLevel() == null) {
            hfPrjUnitBase.setSecretLevel(1);
        }

        HfPrjUnitClassify classify = hfPrjUnitClassifyService.getById(hfPrjUnitBase.getClassifyId());
        if (classify != null) {
            hfPrjUnitBase.setClassifyName(classify.getClassifyName());
        }
        //判断编号是否重复add
        QueryWrapper<HfPrjUnitBase> queryWrapper = new QueryWrapper<HfPrjUnitBase>();
        queryWrapper.lambda().ne(HfPrjUnitBase::getDelFlag, 1);
        queryWrapper.eq("unit_code", hfPrjUnitBase.getUnitCode());
        int count = hfPrjUnitBaseService.count(queryWrapper);
        if (count > 0) {
            return BusiResponse.error(400, String.format("项目编码[%s]已经存在！", hfPrjUnitBase.getUnitCode()));
        }


        hfPrjUnitBase.setUpdateUserId(SystemLoginUser.userId);
        hfPrjUnitBase.setUpdateUserName(SystemLoginUser.idName);
        hfPrjUnitBase.setUpdateTime(new Date());

        hfPrjUnitBaseService.save(hfPrjUnitBase);

        String unitName = hfPrjUnitBase.getUnitName();

        autoLogUtils.addLog("环境试验-试验项目", String.format("新增试验项目:【%s】", unitName));

        return BusiResponse.ok("添加成功");
    }


    @PostMapping(value = "/edit")
    @ApiOperation(value = "项目-检测项目功能:编辑")
    public BusiResponse edit(@RequestBody HfPrjUnitBase hfPrjUnitBase) {
        if (hfPrjUnitBase.getSecretLevel() == null) {
            hfPrjUnitBase.setSecretLevel(1);
        }
        hfPrjUnitBase.setUpdateUserId(SystemLoginUser.userId);
        hfPrjUnitBase.setUpdateUserName(SystemLoginUser.idName);
        hfPrjUnitBase.setUpdateTime(new Date());

        HfPrjUnitClassify classify = hfPrjUnitClassifyService.getById(hfPrjUnitBase.getClassifyId());
        if (classify != null) {
            hfPrjUnitBase.setClassifyName(classify.getClassifyName());
        }
        //判断编号是否重复add
        QueryWrapper<HfPrjUnitBase> queryWrapper = new QueryWrapper<HfPrjUnitBase>();
        queryWrapper.lambda().ne(HfPrjUnitBase::getDelFlag, 1)
                .ne(HfPrjUnitBase::getId, hfPrjUnitBase.getId());
        queryWrapper.eq("unit_code", hfPrjUnitBase.getUnitCode());

        int count = hfPrjUnitBaseService.count(queryWrapper);
        if (count > 0) {
            return BusiResponse.error(400, String.format("项目编码[%s]已经存在！", hfPrjUnitBase.getUnitCode()));
        }

        hfPrjUnitBaseService.updateById(hfPrjUnitBase);

        String unitName = hfPrjUnitBase.getUnitName();

        autoLogUtils.modifyLog("环境试验-试验项目", String.format("编辑试验项目:【%s】", unitName));
        return BusiResponse.ok("编辑成功！");
    }


    @GetMapping("/queryById")
    @ApiOperation(value = "项目-检测项目功能:根据id查询数据")
    public BusiResponse queryById(@RequestParam("id") String id) {
        HfPrjUnitBase byId = hfPrjUnitBaseService.getById(id);
        // 查询转换附件
        return BusiResponse.OK(byId);
    }


    @PostMapping("/delete")
    @ApiOperation(value = "项目-检测项目功能:逻辑删除")
    public BusiResponse delete(@RequestBody List<String> idList) {
        List<HfPrjUnitBase> unitBaseList = hfPrjUnitBaseService.listByIds(idList);
        hfPrjUnitBaseService.removeByIds(idList);
        String unitCodes = unitBaseList.stream()
                .map(HfPrjUnitBase::getUnitCode)
                .collect(Collectors.joining(","));
        autoLogUtils.deleteLog("环境试验-试验项目", String.format("删除了试验项目:【%s】", unitCodes));
        return BusiResponse.ok("删除成功！");
    }

    @PostMapping("/exportExcel")
    @ApiOperation(value = "项目-检测项目功能:导出数据")
    public Object exportExcel(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        if (pageInfo == null) {
            return BusiResponse.error("参数有误！");
        }
        BusiResponse export = hfPrjUnitBaseService.exportExcel(pageInfo);
        if (export.getCode() == com.hifar.fw.utils.bean.BusiConst.CODE_SUCCESS) {
            String encode = null;
            try {
                encode = URLEncoder.encode("项目-检测项目.xlsx", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/vnd.ms-excel");
            headers.add("Access-Control-Expose-Headers", "Content-Disposition");
            headers.add("Content-Disposition", "filename=" + encode);

            autoLogUtils.exportLog("环境试验-试验项目", "导出试验项目列表");
            return ResponseEntity.status(HttpStatus.OK).headers(headers).body((byte[]) export.getData());
        }
        return export;
    }

    @PostMapping("/importExcel")
    @ApiOperation(value = "项目-检测项目功能:导入excel数据")
    public BusiResponse importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return BusiResponse.error("文件为空！");
        } else {
            if (ExcelTemplateUtil.isExcelFile(file)) {
                autoLogUtils.exportLog("环境试验-试验项目", "导入试验项目列表");
                return hfPrjUnitBaseService.importExcel(file);
            } else {
                return BusiResponse.error("请上传excel文件！");
            }
        }
    }


    @GetMapping("/listUnitStandard")
    @ApiOperation(value = "查询项目下依据标准")
    public BusiResponse listUnitStandard(@RequestParam("id") String id) {
        List<HfResStandard> standardList = hfPrjUnitBaseService.listUnitStandard(id);
        return BusiResponse.OK(standardList);
    }

    @GetMapping("/queryUnitByCode")
    @ApiOperation("根据项目代号查询项目信息")
    public BusiResponse queryUnitByCode(@RequestParam("unitCode") String unitCode) {
        QueryWrapper<HfPrjUnitBase> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(HfPrjUnitBase::getUnitCode, unitCode);
        HfPrjUnitBase hfPrjUnitBase = hfPrjUnitBaseService.getOne(queryWrapper);
        return BusiResponse.OK(hfPrjUnitBase);
    }


}